﻿<link href="/pwccnhk/gtsventure/Admin/HomePage/DownloadFile?fileIds=843e3cc9-2d2b-4f13-a4d3-9e5e5936f1d6" rel="stylesheet" />
<script src="/pwccnhk/gtsventure/Admin/HomePage/DownloadFile?fileIds=847d2167-ccfb-404b-b0e3-b2fb54509a91"> </script>
<script src="/pwccnhk/gtsventure/Admin/HomePage/DownloadFile?fileIds=c5cf503f-ffde-49c4-ba81-ece59095c814"> </script>
<script src="/pwccnhk/gtsventure/Admin/HomePage/DownloadFile?fileIds=9afb4878-4c7e-48cb-9674-85aff2fe07d0"> </script>
<script src="/pwccnhk/gtsventure/Admin/HomePage/DownloadFile?fileIds=b21a8457-24f9-452f-bfae-c94df0c31f59"></script>
<script type="text/javascript" src="/pwccnhk/gtsventure/Admin/HomePage/DownloadFile?fileIds=c331d882-4762-4d8e-b0d5-dbb4dcd9c6ba&v=9.5"></script>

<script type='text/javascript'>
    /*
    javascript code
    */
    var metaCount = 20;
var expDays = 0;
var dataId = $("input[name='_id']").val();

AppDesign.Document.loading();
AppDesign.Field("C4-FavouriteCount").hide();
AppDesign.Field("C4-Share").hide();
AppDesign.Field("C4-EditHistory").hide();
AppDesign.Field("DocumentOwner").disabled();
AppDesign.Field("CheckTime").hide();
AppDesign.Field("C4-WorkflowStateDisplayName").hide();
AppDesign.Field("C4-Comments").hide();
AppDesign.Field("ProductLine").hide();
AppDesign.Field("ProjectsLise").hide();
AppDesign.Field("Engagement").hide();
AppDesign.Field("VersionNum").hide();
  


var currUser;
var applicationUrl = "";
AppDesign.User(function (user) {
    currUser = user;
    console.log(currUser);
    applicationUrl = getApplicationUrl();
    pageLoad();
});

//到期时间差：日
$("#Metadata-ExpirationDate").on("input propertychange", function () {
    var cDays = daysBetween(new Date(), AppDesign.Field("ExpirationDate").getValue());
    AppDesign.Field("ExpirationDays").setValue(cDays);
});

//页面查看权限判断
function PowerLimit() {
    var editor = AppDesign.Field("RestrictedEditor").getValue();
    var reader = AppDesign.Field("RestrictedReader").getValue();
    var editorGroup = AppDesign.Field("RestrictedEditor").getValue().split('|C4|');
    var editorGroupExit = compareArray(editorGroup);
    var readerGroup = AppDesign.Field("RestrictedReader").getValue().split('|C4|');
    var readerGroupExit = compareArray(readerGroup);
    var owner = AppDesign.Field("DocumentOwner").getValue();
    if (editor == "" || reader == "" || currUser.StaffCode == owner || editor.indexOf(currUser.StaffCode) > -1 || editorGroupExit == true || reader.indexOf(currUser.StaffCode) > -1 || readerGroupExit == true) {
    }
    else {
        AppDesign.Dialog.alert("", "You have no right to view the document.", AppDesign.Dialog.TYPE_DANGER);
        setTimeout(function () {
            winExit();
        }, 1500);
        return false;
    }
}

//Check out后页面编辑权限
function PowerCheckOut() {
    var checkStatus = AppDesign.Field("CheckStatus").getValue();
    if (checkStatus == "Checked Out" && currUser.StaffCode != AppDesign.Field("CheckCreatorId").getValue()) {
        AppDesign.Dialog.alert("", "You have no right to edit the document.", AppDesign.Dialog.TYPE_DANGER);
        setTimeout(function () {
            winExit();
        }, 2000);
        return false;
    }
}

//页面初始化
function pageLoad() {

    LoadProductEngagementData();
    var pagemode = AppDesign.Document.pageMode;
    if (pagemode == "add") {

        AppDesign.Field("UploadMethod").setValue("Single");
        AppDesign.Section("DocumentMultipleFile").hide();
        AppDesign.Field("DocumentMultipleFile").removeValidation();

        AppDesign.ActionButton("Save").show();
        AppDesign.Field("VersionNum").setValue("1.00");
        AppDesign.Field("C4-WorkflowStateDisplayName").setValue("Published");
        AppDesign.Field("DocumentOwner").setValue(currUser.StaffCode);
        AppDesign.Field("CheckCreator").setValue(currUser.StaffName);
        AppDesign.Field("CheckCreatorId").setValue(currUser.StaffCode);
        AppDesign.Field("CreatorEmail").setValue(currUser.UserInfo.Email);
        AppDesign.Field("CheckStatus").setValue("Checked In"); //Checked In、Checked Out
        AddLoadMetaData();
        processDMSSource();
    } else if (pagemode == "edit") {
        PowerCheckOut();
        PowerLimit();
        OtherLoadMetaData();

        var uploadMethod = AppDesign.Field("UploadMethod").getValue();
        if (uploadMethod == "Multiple") {
            AppDesign.Section("DocumentFile").hide();
            AppDesign.Section("DocumentMultipleFile").show();
            AppDesign.Field("DocumentFile").removeValidation();
        } else {
            AppDesign.Section("DocumentFile").show();
            AppDesign.Section("DocumentMultipleFile").hide();
            AppDesign.Field("DocumentMultipleFile").removeValidation();
        }

        var expDate = AppDesign.Field("ExpirationDate").getValue();
        $('#Metadata-ExpirationDate').data("DateTimePicker").minDate(addDay(expDays));
        AppDesign.Field("ExpirationDate").setValue(expDate);

        var checkStatus = AppDesign.Field("CheckStatus").getValue();
        if (checkStatus == "Checked Out" && currUser.StaffCode == AppDesign.Field("CheckCreatorId").getValue()) {
            AppDesign.ActionButton("Save").show();
            AppDesign.ActionButton("Check In").show();
        }
    } else {
        $("#baseHeader").show();
        $("#baseHeaderIcon").click(function(){
            if($(this).hasClass("glyphicon-menu-up")){
                $(this).removeClass("glyphicon-menu-up");
                $(this).addClass("glyphicon-menu-down");
                AppDesign.Field("Tag").hide();
                AppDesign.Field("RestrictedEditor").hide();
                AppDesign.Field("RestrictedReader").hide();
                AppDesign.Field("DocumentOwner").hide();
                AppDesign.Field("VersionNum").hide();
                AppDesign.Field("ExpirationDate").hide();
            }
            else{
                $(this).removeClass("glyphicon-menu-down");
                $(this).addClass("glyphicon-menu-up");
                AppDesign.Field("Tag").show();
                AppDesign.Field("RestrictedEditor").show();
                AppDesign.Field("RestrictedReader").show();
                AppDesign.Field("DocumentOwner").show();
                AppDesign.Field("VersionNum").show();
                AppDesign.Field("ExpirationDate").show();
            }
        });
        $("#baseHeaderIcon").click();
        $('div[name="DIV_MetaData1').parent().parent().parent().parent().hide();

        PowerLimit();
        var checkStatus = AppDesign.Field("CheckStatus").getValue();
        if (checkStatus == "Checked Out" && currUser.StaffCode == AppDesign.Field("CheckCreatorId").getValue()) {
            window.location.href = 'https://appcnhkdm450.digitalmaker.asia.pwcinternal.com/pwccnhk/gtsventure/vForm/Document/Edit/' + $("input[name='_id']").val();
        }
        AppDesign.Field("UploadMethod").hide();
        var uploadMethod = AppDesign.Field("UploadMethod").getValue();
        if (uploadMethod == "Multiple") {
            AppDesign.Section("DocumentFile").hide();
            AppDesign.Section("DocumentMultipleFile").show();
        } else {
            AppDesign.Section("DocumentFile").show();
            AppDesign.Section("DocumentMultipleFile").hide();
        }

        AppDesign.ActionButton("Close").hide();
        $("#div_Spportformat").hide();
        var checkStatus = AppDesign.Field("CheckStatus").getValue();
        if (checkStatus == "Checked Out") {
            //$("div[class='checkout-cover']").show();
            //$("#Checkusername").html(AppDesign.Field("CheckCreator").getValue());
            $('div[name="DIV_Title"]').append("<p>The file was checked out, please contact <span>"+AppDesign.Field("CheckCreator").getValue()+"</span> ,if you need to edit the content.</p>");
        }

        var pName = AppDesign.Field("Title").getValue() + "." + AppDesign.Field("DocumentType").getValue();
        $("#label-PreviewTitle").html(pName);
        AppDesign.Field("Title").setValue(pName);
        //AppDesign.Field("C4-FavouriteCount").show();
        AppDesign.Field("C4-Share").show();
        AppDesign.Field("C4-Comments").show();
        AppDesign.Field("C4-EditHistory").show();
        var className = "control-" + checkStatus.replace(' ', '');
        $("#label-Title").prepend("<div class='file-image'></div>");
        var murl = getPIC(AppDesign.Field("DocumentType").getValue());
        $("div[class='file-image']").css("background-image", "url(" + murl + ")");
        OtherLoadMetaData();

        var editorlist = AppDesign.Field("RestrictedEditor").getValue();
        var editorGroup = AppDesign.Field("RestrictedEditor").getValue().split('|C4|');
        var editorGroupExit = compareArray(editorGroup);
        if (currUser.StaffCode == AppDesign.Field("DocumentOwner").getValue() || editorlist == "" || editorlist.indexOf(currUser.StaffCode) > -1 || editorGroupExit == true) {
            var state = AppDesign.Field("C4-WorkflowStateDisplayName").getValue();
            if (checkStatus == "Checked In" && state == "Published") {
                $("#imgUnLock").show();
            }
        }

        initVersionHistory();

    }
}



//upload上传文件:single
_xDropzoneArray['DocumentFile'].on("addedfile", function (file) {
    if (_xDropzoneArray['DocumentFile'].files.length == 1) {
        var fileName = file.name;
        var suffix = fileName.substr(fileName.lastIndexOf(".") + 1);
        var title = fileName.substr(0, fileName.lastIndexOf("."));
        //AppDesign.Field("Title").setValue(title);
        AppDesign.Field("DocumentType").setValue(suffix);
        AppDesign.Field("DocumentSize").setValue(getDocumentSize(file.size));
        AppDesign.Field("DocumentNum").setValue(1);
        var format = "";
        switch (suffix.toLowerCase()) {
            case "doc":
                format = "Word";
                break;
            case "docx":
                format = "Word";
                break;
            case "xls":
                format = "Excel";
                break;
            case "xlsx":
                format = "Excel";
                break;
            case "pdf":
                format = "PDF";
                break;
            case "ppt":
                format = "PPT";
                break;
            case "pptx":
                format = "PPT";
                break;
            case "gif":
                format = "Image";
                break;
            case "jpeg":
                format = "Image";
                break;
            case "jpg":
                format = "Image";
                break;
            case "bmp":
                format = "Image";
                break;
            case "png":
                format = "Image";
                break;
            case "tif":
                format = "Image";
                break;
            case "tiff":
                format = "Image";
                break;
            default:
                format = "Other";
                break;
        }
        AppDesign.Field("Format").setValue(format);
    }
});

//upload删除文件:single
_xDropzoneArray['DocumentFile'].on("removedfile", function (file) {
    if (_xDropzoneArray['DocumentFile'].files.length == 0) {
        AppDesign.Field("Title").setValue("");
        AppDesign.Field("DocumentType").setValue("");
        AppDesign.Field("DocumentSize").setValue("");
        AppDesign.Field("DocumentNum").setValue(0);
        AppDesign.Field("Format").setValue("");
    }
});


//获取浏览器参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return ''; //返回参数值
};


//Add初始化Meta Data（获取配置信息）
function AddLoadMetaData() {
    for (var m = 1; m <= metaCount; m++) {
        $('div[name="DIV_MetaData' + m.toString() + '"]').hide();
    }

    var settings;
    var requrl = applicationUrl + "/customapi/RetrieveQueryDocs";
    var Jsondata = {};
    Jsondata.Token = "";
    Jsondata.EntityName = "syfmbzl81dc";
    Jsondata.index = 0;
    Jsondata.size = 1;
    var searchItem = [];
    var searchValue = "";
    var locationUrl = window.location.href;
    if (locationUrl.indexOf("?") > -1) {
        searchValue = getUrlParam("DocumentType");
    }
    searchItem.push({
        Method: "And",
        Operator: "Equal",
        Name: "Code",
        Value: searchValue
    });
    Jsondata.SearchItem = searchItem;

    $.post(requrl, Jsondata, function (result) {
        if (result.StatusCode == 200) {
            if (result.Data.total > 0) {
                settings = result.Data.rows[0];
                console.log(settings);
                AppDesign.Field("ContentType").setValue(settings.Code);
                AppDesign.Field("ContentTypeName").setValue(settings.Name);
                AppDesign.Field("Tag").setValue(settings.Tags.join(','));
                if (!isNull(settings.MetaDataTitle)) {
                    $("#div_IndustryMeta").find("h4").html(settings.MetaDataTitle);
                    AppDesign.Field("CMetaDataTitle").setValue(settings.MetaDataTitle);
                }

                $('#Metadata-ExpirationDate').data("DateTimePicker").minDate(addDay(expDays));
                var today = new Date();
                var duration = isNaN(parseInt(settings.RetentionDuration)) ? 1 : parseInt(settings.RetentionDuration);
                var y = today.getFullYear() + duration;
                var m = (today.getMonth() + 1) > 9 ? (today.getMonth() + 1) : "0" + (today.getMonth() + 1);
                var d = today.getDate() > 9 ? today.getDate() : "0" + today.getDate();
                var expDate = y + "-" + m + "-" + d;
                AppDesign.Field("ExpirationDate").setValue(expDate);

                var MetaDataList = {};
                $.each(settings, function (index, item) {
                    if (index.indexOf("MetaData") > -1) {
                        eval("MetaDataList." + index + "='" + item + "'");
                    }
                });

                console.log(MetaDataList);
                var industryHide = false;
                $.each(MetaDataList, function (index, item) {
                    if (index.indexOf("Display") == -1) {
                        $('label[for="Metadata-' + index + '"]').html(item);
                    }
                    if (index.indexOf("Display") > -1 && index.indexOf("c4value") == -1 && item == "Yes") {
                        $('div[name="DIV_' + index.substr(0, index.indexOf("Display")) + '"]').show();
                        industryHide = true;
                    }
                });
                AppDesign.Field("MetaDataTitle").setValue(JSON.stringify(MetaDataList));
                $("#div_IndustryMeta").show();
                if (!industryHide) {
                    $("#div_IndustryMeta").hide();
                }
            } else {
                $('#Metadata-ExpirationDate').data("DateTimePicker").minDate(addDay(expDays));
                var today = new Date();
                var duration = 10;
                var y = today.getFullYear() + duration;
                var m = (today.getMonth() + 1) > 9 ? (today.getMonth() + 1) : "0" + (today.getMonth() + 1);
                var d = today.getDate() > 9 ? today.getDate() : "0" + today.getDate();
                var expDate = y + "-" + m + "-" + d;
                AppDesign.Field("ExpirationDate").setValue(expDate);
                $("#div_IndustryMeta").hide();
            }
        }
        AppDesign.Document.endLoading();
    });
}


//其他类型初始化Meta Data
function OtherLoadMetaData() {
    for (var m = 1; m <= metaCount; m++) {
        $('div[name="DIV_MetaData' + m.toString() + '"]').hide();
    }

    if (!isNull(AppDesign.Field("CMetaDataTitle").getValue())) {
        $("#div_IndustryMeta").find("h4").html(AppDesign.Field("CMetaDataTitle").getValue());
    }

    if (AppDesign.Field("MetaDataTitle").getValue() != "") {
        var MetaDataList = JSON.parse(AppDesign.Field("MetaDataTitle").getValue());
        var industryHide = false;
        $.each(MetaDataList, function (index, item) {
            if (index.indexOf("Display") == -1) {
                $('label[for="Metadata-' + index + '"]').html(item);
            }
            if (index.indexOf("Display") > -1 && index.indexOf("c4value") == -1 && item == "Yes") {
                $('div[name="DIV_' + index.substr(0, index.indexOf("Display")) + '"]').show();
                industryHide = true;
            }
        });
        if (!industryHide) {
            $("#div_IndustryMeta").hide();
        }
    } else {
        $("#div_IndustryMeta").hide();
    }
    AppDesign.Document.endLoading();
}



//二维码鼠标事件
$("#qrcode").hover(function () {
    var objDiv = $("#larqrcode");
    $(objDiv).css("display", "block");
}, function () {
    var objDiv = $("#larqrcode");
    $(objDiv).css("display", "none");
});


//Checked In/Out
function UpdateCheckStatus(ActionType) {
    if (ActionType == "Checked In" && currUser.StaffCode != AppDesign.Field("CheckCreatorId").getValue()) {
        var message = "The document has been checked out by " + AppDesign.Field("CheckCreator").getValue() + "!";
        AppDesign.Dialog.alert("", message, AppDesign.Dialog.TYPE_DANGER);
        return false;
    }

    var message = "Are you sure you want to check in?";
    if (ActionType == "Checked Out") {
        message = "Are you sure you want to check out?";
    }
    AppDesign.Dialog.confirm("", message,
        function () {
            var requrl = applicationUrl + "/customapi/BatchUpdateDocs";
            var Jsondata = {};
            Jsondata.Token = "";
            Jsondata.DocIds = [$("input[name='_id']").val()];
            var fields = {};
            fields.CheckStatus = ActionType;
            fields.CheckCreator = currUser.StaffName;
            fields.CheckCreatorId = currUser.StaffCode;
            Jsondata.StaffId = currUser.StaffCode;
            Jsondata.StaffName = currUser.StaffName;
            fields.CheckTime = Date.parse(new Date());
            Jsondata.FieldsValue = fields;
            Jsondata.ActionCode = "";
            Jsondata.EntityName = "Document";
            Jsondata.CurrentUserRole = [];
            Jsondata.ActionMessage = ActionType;
            Jsondata.UpdateWorkflowArgs = false;
            Jsondata.Items = null;
            console.log(Jsondata);
            $.post(requrl, Jsondata, function (result) {
                console.log(result);
                if (result.StatusCode == 200) {
                    window.location.href = applicationUrl + "/vForm/Document/Edit/" + dataId;
                }
            });
        },
        function () {
            console.log("Nope")
        }, AppDesign.Dialog.TYPE_DANGER);
}

//初始化Product,Engagement,projedct
function LoadProductEngagementData() {
    var searchObj = {
        "EntityName": "jz4v85otzw",
        "DisplayField": {
            "value": "_id",
            "title": "ProductName",
            "subTitle": "CollaborationPortal",
            "desc": "ProductName"
        },
        "SearchField": ["ProductName", "CollaborationPortal"],
        "Order": {
            "ProductName": "Ascending"
        },
        "index": 0,
        "size": 10
    };
    AppDesignExt.DataPicker(AppDesign.Document.pageMode, "ProductLine", "ProductCode", "Select Product", searchObj, 1, function (items) {

    });


    var searchObj = {
        "EntityName": "85eab984-e6a2-4f93-a2a0-5a5421e0137f",
        "DisplayField": {
            "value": "_id",
            "title": "ProjectName",
            "subTitle": "Region",
            "desc": ""
        },
        "SearchField": ["ProjectName", "Region"],
        "Order": {
            "ProjectName": "Ascending"
        },
        "index": 0,
        "size": 10
    };
    AppDesignExt.DataPicker(AppDesign.Document.pageMode, "Engagement", "EngagementCode", "Select Engagement", searchObj, 1, function (items) {

    });

    var searchObj = {
        "EntityName": "7m2ncu0h5i",
        "DisplayField": {
            "value": "_id",
            "title": "ProjectNameNew",
            "subTitle": "Status",
            "desc": "ProjectNameNew"
        },
        "SearchField": ["ProjectName", "Status"],
        "Order": {
            "ProjectName": "Ascending"
        },
        "index": 0,
        "size": 10
    };
    AppDesignExt.DataPicker(AppDesign.Document.pageMode, "ProjectsLise", "ProjectCode", "Select Project", searchObj, 1, function (items) {

    });



}

//计算加天数后日期
function addDay(dayNumber) {
    var later = new Date();
    later.setDate(later.getDate() + parseInt(dayNumber));
    var y = later.getFullYear();
    var m = (later.getMonth() + 1) > 9 ? (later.getMonth() + 1) : "0" + (later.getMonth() + 1);
    var d = later.getDate() > 9 ? later.getDate() : "0" + later.getDate();
    var newDate = y + "-" + m + "-" + d;
    return newDate;
}


//计算两个日期天数差
function daysBetween(sDate1, sDate2) {
    var time1 = Date.parse(new Date(sDate1));
    var time2 = Date.parse(new Date(sDate2));
    var nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24)) - 1;
    return nDays;
};


//获取类型图片
function getPIC(type) {
    var url = "";
    switch (type.toLowerCase()) {
        case "bmp":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=acc50cba-ed2b-4bbc-b561-a8cf6727198a";
            break;
        case "doc":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=1890c1e5-285d-4caf-b0fa-a9d2857810c3";
            break;
        case "docx":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=c7be3852-06b7-4194-bf55-b8d1cb03005a";
            break;
        case "gif":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=24146ab5-8c2b-44c8-99b9-9bb5b5ba5192";
            break;
        case "jpeg":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=16cadfd6-9cbe-4502-8c07-2d95637e5ecf";
            break;
        case "jpg":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=fd7f0cb0-d75b-4bf7-991f-4800784c9d6b";
            break;
        case "pdf":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=510ac995-ec32-406f-a226-2fb482c4c6cb";
            break;
        case "ppt":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=e280f0fd-96d3-4a50-9aa4-21b727b4eeed";
            break;
        case "pptx":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=41ded375-18d0-45be-8bcd-b0d51fa4eaac";
            break;
        case "psd":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=1db23ae4-6629-4b23-811c-ed7dced76ee2";
            break;
        case "tif":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=68becab6-76bc-4250-ab20-3ec74abaf791";
            break;
        case "tiff":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=ae59c933-d6d9-4d68-86ff-e9a0589d6ccc";
            break;
        case "vsd":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=5e446f1b-ac3a-48ef-a2fb-7b9d221c7f0f";
            break;
        case "vsdx":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=ae6301ca-7568-4ebb-a7e6-afdb0bb0633a";
            break;
        case "xls":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=9c4e801b-c09c-45c9-90e8-eab4c129c2e5";
            break;
        case "xlsx":
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=4d90d6fe-a161-4fd2-ab4e-9ace88d7a676";
            break;
        default:
            url = applicationUrl + "/Admin/HomePage/DownloadFile?fileIds=510ac995-ec32-406f-a226-2fb482c4c6cb";
            break;

    }
    return url;
}


//关闭窗口
function winExit() {
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        window.opener = null;
        window.close();
    } else if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") != -1) {
        window.location.href = 'about:blank';
        window.close();
    } else {
        window.opener = null;
        window.open('', '_self', '');
        window.close();
    }
}


//判断输入字符串是否为空或者全部都是空格
function isNull(str) {
    if (str == "") return true;
    var regu = "^[ ]+$";
    var re = new RegExp(regu);
    return re.test(str);
}

//获取浏览器地址
function getApplicationUrl() {
    var locationHref = window.location.href.split("//");
    var http = locationHref[0];
    var host = locationHref[1].split("/");
    var searchUrl = http + "//" + host[0] + "/" + host[1] + "/" + host[2];
    return searchUrl;
}

//计算上传文件大小
function getDocumentSize(fileSize) {
    var result = "";
    var kSize = (fileSize / 1000.0).toFixed(1);
    if (kSize >= 1024) {
        var mSize = (kSize / 1024.0).toFixed(1);
        if (mSize >= 1024) {
            var gSize = (mSize / 1024.0).toFixed(1);
            result = gSize.toString() + "GB";
        } else {
            result = mSize.toString() + "MB";
        }
    } else {
        result = kSize.toString() + "KB";
    }
    return result;
}


//当前用户组和Reader、Editor比较
function compareArray(comGroup) {
    var userGroup = currUser.UserInfo.Groups;
    var exit = false;
    for (var m = 0; m < userGroup.length; m++) {
        var user = userGroup[m];
        for (var n = 0; n < comGroup.length; n++) {
            var com = comGroup[n].replace('@', '');
            if (user == com) {
                exit = true;
                break;
            }
        }
        if (exit) {
            break;
        }
    }
    return exit;
}

//Restriction Type改变事件
$('input:radio[name="UploadMethod_show"]').change(function () {
    var restType = AppDesign.Field("UploadMethod").getValue();
    if (restType == "Single") {
        AppDesign.Section("DocumentFile").show();
        AppDesign.Section("DocumentFile").setValidation();
        AppDesign.Section("DocumentMultipleFile").hide();
        AppDesign.Field("DocumentMultipleFile").removeValidation();
        _xDropzoneArray['DocumentMultipleFile'].removeAllFiles();
    } else {
        AppDesign.Section("DocumentFile").hide();
        AppDesign.Section("DocumentFile").removeValidation();
        AppDesign.Section("DocumentMultipleFile").show();
        AppDesign.Field("DocumentMultipleFile").setValidation();
        _xDropzoneArray['DocumentFile'].removeAllFiles();
        AppDesign.Field("DocumentType").setValue("Multiple");
        AppDesign.Field("Format").setValue("Multiple");
    }
});

//Multiple计算文件数量和大小
function multipleFileSum() {
    var restType = AppDesign.Field("UploadMethod").getValue();
    if (restType == "Multiple") {
        var fileData = JSON.parse($("#Metadata-DocumentMultipleFile").val());
        var fileSizeByte = 0;
        var fileNum = 0;
        $.each(fileData, function (index, item) {
            fileNum++;
            var fileSize = parseFloat(item.fileSize);
            var fileUnit = item.fileUnit;
            switch (fileUnit.toLowerCase()) {
                case "kb":
                    fileSizeByte += fileSize * 1024;
                    break;
                case "mb":
                    fileSizeByte += fileSize * 1024 * 1024;
                    break;
                case "gb":
                    fileSizeByte += fileSize * 1024 * 1024 * 1024;
                    break;
                default:
                    break;
            }
        });
        AppDesign.Field("DocumentSize").setValue(getDocumentSize(fileSizeByte));
        AppDesign.Field("DocumentNum").setValue(fileNum);
    }
}

//Save
AppDesign.ActionButton("Save").on('click', function () {
    multipleFileSum();
});

//Check In
AppDesign.ActionButton("Check In").on('click', function () {
    $("#checkInModal").modal('show');
});

//Configm OK
$("#btnCheckOK").on('click', function () {
    multipleFileSum();
    var versionType = $("input[name='checkInRad']:checked").val();
    var versionNum = AppDesign.Field("VersionNum").getValue();
    if (versionType == "New") {
        versionNum = (parseInt(versionNum) + 1).toFixed(2);
    }
    else {
        versionNum = (parseFloat(versionNum) + 0.01).toFixed(2);
    }
    AppDesign.Field("VersionNum").setValue(versionNum);
    AppDesign.ActionButton("Check In Back").click();
});


//Configm Cancel
$("#btnCheckCancel").on('click', function () {
    $("#checkInModal").modal('hide');
});


//load history version
function initVersionHistory() {
    $("#historyTable").grid({
        id: "historyTable",
        entityname: "cb04e3cd-4b84-4406-92ec-d22cd7f2b20a",
        searchitem: [{
            Method: "And",
            Operator: "Equal",
            Name: "ForeignID",
            Value: dataId
        }],
        columns: ["VersionNum", "C4-ModifyBy", "C4-ModifyDate"],
        displaycolumns: ["Version No.", "Operator", "Operating time"],
        pagesize: 5,
        childPage: true,
        childPageUrl: "https://appcnhkdm450.digitalmaker.asia.pwcinternal.com/pwccnhk/gtsventure/vForm/DocumentHistory/Preview/",
        callback: function (items) { }
    });
}


//获取url参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return ''; //返回参数值
};

function processDMSSource(){
    
    if(PageMode != "add")return;
    AppDesign.Field("Tag").setValue(getUrlParam("ProductName"));
    var editors=getUrlParam("BusinessManager")+"|C4|"+getUrlParam("ProductManager");
    AppDesign.Field("RestrictedEditor").setValue(editors);

    AppDesign.Field("DocType").setValue("Document");
    var OpportunityId=getUrlParam("OpportunityId");
    if(OpportunityId!=""){
        AppDesign.Field("Source").setValue("Opportunity");
        AppDesign.Field("SourceLink").setValue("pwccnhk/gtsventure/vForm/NewOpportunities/Preview/"+OpportunityId);       
        return;
    }
    var productId=getUrlParam("ProductId");
    if(productId!=""){
        AppDesign.Field("Source").setValue("Product Material");
        AppDesign.Field("SourceLink").setValue("pwccnhk/gtsventure/vForm/Product/Preview/"+productId);       
        return;
    }
    var projectId=getUrlParam("ProjectId");
    if(projectId!=""){
        AppDesign.Field("Source").setValue("Project Material");
        AppDesign.Field("SourceLink").setValue("pwccnhk/gtsventure/vForm/ProjectManagement/Preview/"+projectId);       
        return;
    }
    AppDesign.Field("Source").setValue("DMS");
    AppDesign.Field("SourceLink").setValue("pwccnhk/gtsventure/vForm/Document/Preview/"+dataId);
    
}


</script>